import time
import uuid
from xml.dom.minidom import Document
# 创建全局DOM文档对象
doc = Document()


def add_xml_ele(child_ele_name, parent_ele, child_ele_text=None):
    """
    为父节点对象添加子节点对象
    :param child_ele_name:  子节点名称
    :param parent_ele:      父节点对象
    :param child_ele_text:  子节点内容文本
    :return:
    """
    # 创建子节点
    child_ele = doc.createElement(child_ele_name)
    # 父节点添加子节点
    parent_ele.appendChild(child_ele)
    if child_ele_text:
        # 添加文本
        child_ele.appendChild(doc.createTextNode(child_ele_text))


# 创建根元素
message_ele = doc.createElement('Message')
# 引用本地XML Schema
doc.appendChild(message_ele)
# ===== 创建MessageHeader元素 =====
message_header_ele = doc.createElement('MessageHeader')
add_xml_ele(child_ele_name='Version', parent_ele=message_header_ele, child_ele_text='2.0')
message_ele.appendChild(message_header_ele)
# ===== 创建MessageHeader元素 =====

# ===== 创建MessageBody元素 =====
message_body_ele = doc.createElement('MessageBody')
# 设置属性
message_body_ele.setAttribute('Type', "ViolationInfo")
# <!--禁止采用此笔违法（0 - 否，1 - 是，为空时当作“否”处理，此字段为特定业务使用字段），设备采集的数据可忽略 -->
add_xml_ele(child_ele_name='VioNotUse', parent_ele=message_body_ele, child_ele_text='0')
# < NoticeSn > 5101010136945296 < / NoticeSn > <!--集成指挥平台返回的违停提醒上传序号，设备采集的数据可忽略 -->
add_xml_ele(child_ele_name='NoticeSn', parent_ele=message_body_ele, child_ele_text=' ')
# <RecogSys>   <!--一二次识别采集系统标识码-->
add_xml_ele(child_ele_name='RecogSys', parent_ele=message_body_ele, child_ele_text='R02')
# < Direction > 行驶方向 < / Direction > <!--见行驶路段方向编码 -->

# < RecTime > 记录生成时间 < / RecTime > <!--格式yyyy-mm-dd HH:MM:SS.zzz -->
cms = (time.time() - int(time.time())) * 1000
rec_time = "%s.%03d" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), cms)
add_xml_ele(child_ele_name='RecTime', parent_ele=message_body_ele, child_ele_text=rec_time)
message_ele.appendChild(message_body_ele)
# ===== 创建message_body_ele元素 =====

f_name_full = f'./xml/{uuid.uuid4()}.xml'
with open(f_name_full, 'w', encoding='utf-8') as f:
    doc.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')

print(f"Write to {f_name_full} OK")

